//
//  THJUserVC.m
//  THJXHW
//
//  Created by 河南德艺 on 17/3/7.
//  Copyright © 2017年 河南德艺. All rights reserved.
//  "15836313772",

#import "THJUserVC.h"
#import "THJMineIndex_0_Cell.h"
#import "THJMineIndex_1_Cell.h"
#import "THJEditUserInfoVC.h"
#import "THJFabuManageVC.h"
#import "THJMyOrderVC.h"
#import "THJMyFocusVC.h"
#import "THJSettingVC.h"
#import "THJShareAppVC.h"
#import "MJRefresh.h"
#import "THJRzsqCell.h"
#import "THJHjbUserCell.h"
#import "THJMyQiugouVC.h"
#import "THJStoreManageVC.h"
#import "ZBNetworking.h"
#import <SDAutoLayout.h>
#import "THJaAdmitCompanyInfoVC.h"
#import "THJExpressVC.h"
#import "THJLoginVC.h"
#import "LMHWaterFallController.h"
#import "THJMyHjbViewController.h"
#import "THJMyDianJiaOrderVC.h"
#import "THJDianjiaViewController.h"

@interface THJUserVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIWebViewDelegate,THJEditUserInfoVCDelegate>
{
    UITableView * _tableview;
    BOOL isHjbUser;
    BOOL isCompany;
    NSDictionary * CInfoDic;
    
}
@end
@implementation THJUserVC
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = YES;
    [super viewWillAppear:animated];

    [self setStateBarColor:SingleColor(clearColor)];
}
- (void)viewWillDisappear:(BOOL)animated{
    self. navigationController.navigationBar.hidden = NO;
    [super viewWillDisappear:animated];
//    [[LBTabBarController sharedTabBarC].fabuView removeFromSuperview];
//    [self setStateBarColor:MainColor];
}
- (void)viewDidLoad {
    isHjbUser = [[NSUserDefaults standardUserDefaults] boolForKey:@"isHjbUser"];
    isCompany = [[NSUserDefaults standardUserDefaults] boolForKey:@"isCompany"];
    [super viewDidLoad];
    [self getData];
    self.automaticallyAdjustsScrollViewInsets = NO;
   _tableview =  [self setTableviewWithFrame:CGRectMake(0, -20, ScreenWidth, ScreenHeight-50) RegisterNibNameArr:@[@"THJMineIndex_0_Cell",@"THJMineIndex_1_Cell",@"THJHjbUserCell",@"THJRzsqCell"] ReuseIdentifierArr:@[@"cell0",@"cell1",@"hjb",@"rz"] RowHeight:0 BgColor:SingleColor(whiteColor) IsLoadMore:NO];
    //监听登录成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginAction) name:@"login" object:nil];
}
-(void)loginAction{
    NSLog(@"重亲登录");
    [self getData];
}
-(void)getData{
    __weak typeof(self) weekself = self;
    NSString * urlstr = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"index.php?f=member&r=member&m=info"];
    NSLog(@"用户中心url-%@",urlstr);
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    [MBProgressHUD showMessage:@"" toView:self.view];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=urlstr;
        request.apiType=ZBRequestTypeRefresh;
        [request setValue:token forHeaderField:@"token"];
    } success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weekself.view animated:YES];
        NSLog(@"用户中心-%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            CInfoDic = receiveData[@"data"];
            [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"data"][@"userid"] forKey:@"userid"];

            NSNumber * iscompany = receiveData[@"data"][@"is_company"];
            if([iscompany isEqual:@(0)]){
                isCompany = NO;
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isCompany"];
            }else{
                isCompany = YES;
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isCompany"];
            }
            if([receiveData[@"data"][@"alloy_flag"] isEqual:@"0"]){
                isHjbUser = NO;
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isHjbUser"];
            }else{
                NSLog(@"合金宝用户用户用户");
                isHjbUser = YES;
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isHjbUser"];
                NSLog(@"合金宝用户用户用户,%d",[THJTools isHjbUser]);
            }
            [_tableview reloadData];
        }else if([receiveData[@"tip"] isEqual:@"请重新登录"]){
            [THJTabBarController sharedTabBarC].selectedIndex = 0;
            [THJTools signOut];
            [self presentViewController:[THJLoginVC new] animated:YES completion:nil];
        }
    } failed:^(NSError *error){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"error-%@",error);
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            return 200;
        }else{
            return 85;
        }
    }else if(indexPath.section == 2){
        if(isCompany){
            return 44;
        }else{
            return 90;
        }
    }else{
        return 44;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
//        if(isHjbUser){
            return 2;
//        }else{
//            return 1;
//        }
    }else if (section == 3){
        return 3;
    }else if (section == 1){
        if(isHjbUser){
            return 6;
        }else{
            return 2;
        }
        return 6;
    }else if (section == 2){
        if(isCompany){
            return 3;
        }else{
            return 1;
        }
    }
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            THJMineIndex_0_Cell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell0" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0);
            NSLog(@"cinfodic-%@",CInfoDic);
            if(isCompany){
                 cell.companLab.text = CInfoDic[@"company"];
            }else{
                cell.companLab.text = CInfoDic[@"truename"];
            }
           
            [cell.iconImgV sd_setImageWithURL:[NSURL URLWithString:CInfoDic[@"face"]] placeholderImage:kGetImage(@"占位图")];
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconTapAction)];
            [cell.iconImgV addGestureRecognizer:tap];
            return cell;
        }else{
            if(isHjbUser){
                THJHjbUserCell * cell = [tableView dequeueReusableCellWithIdentifier:@"hjb" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                [cell getData];
                return cell;
            }else{
                THJMineIndex_1_Cell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
    }else if(indexPath.section == 1){
        NSArray * titleArr = @[@"编辑信息",@"我的物流",@"我的订单",@"限时抢购",@"我的合金宝",@"我的点价"];
        NSArray * imgNameArr = @[@"bianjixinxi",@"wodewuliu2x",@"wodedingdan2x",@"限时抢购",@"hejin",@"wodewuliu2x"];
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.imageView.image = kGetImage(imgNameArr[indexPath.row]);
        cell.textLabel.text = titleArr[indexPath.row];
        return cell;
    }else if (indexPath.section == 2){
        NSLog(@"企业-%d-%d",isHjbUser,isCompany);
        if(isCompany){
            NSArray * titleArr = @[@"店铺管理",@"我的求购",@"我收到的求购"];
            NSArray * imgArr = @[@"dianpuguanli2x",@"wodeqiugou2x",@"tarenqiugou2x"];
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell4"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell4"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            cell.textLabel.text = titleArr[indexPath.row];
            cell.imageView.image = kGetImage(imgArr[indexPath.row]);
            return cell;
        }else{
            THJRzsqCell * cell = [tableView dequeueReusableCellWithIdentifier:@"rz" forIndexPath:indexPath];
            [cell.renzhengBtn addTarget:self action:@selector(ktQiyeRenZheng) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }else if (indexPath.section == 3){
        NSArray * arr = @[@"设置",@"分享软件给通讯录好友",@"帮助与反馈"];
        NSArray * imgNameArr = @[@"shezhi2x",@"我的分享",@"bangzhu2x"];
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell4"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell4"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = arr[indexPath.row];
        cell.imageView.image = kGetImage(imgNameArr[indexPath.row]);
        return cell;
    }
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        if(indexPath.row == 3){
            [self.navigationController pushViewController:[LMHWaterFallController new] animated:YES];
        }else if(indexPath.row == 4){
            [self.navigationController pushViewController:[THJMyHjbViewController new] animated:YES];
        }else if(indexPath.row == 0){
            THJEditUserInfoVC * vc = [THJEditUserInfoVC new];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 1){
            [self.navigationController pushViewController:[THJExpressVC new] animated:YES];
        }else if(indexPath.row == 2){
             [self.navigationController pushViewController:[THJMyOrderVC new] animated:YES];
        }else if(indexPath.row == 5){
            [self.navigationController pushViewController:[THJDianjiaViewController new] animated:YES];
        }
    }else if(indexPath.section == 2){
        if(isCompany){
            if(indexPath.row == 0){
                THJStoreManageVC * vc = [THJStoreManageVC new];
                vc.cInfoDic = CInfoDic;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                 THJMyQiugouVC * vc = [THJMyQiugouVC new];
                if(indexPath.row == 1){
                    vc.qiugouType = @"buyer";
                }else{
                    vc.qiugouType  = @"seller";
                }
               [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }else if(indexPath.section == 3){
        if(indexPath.row == 0){
            [self.navigationController pushViewController:[THJSettingVC new] animated:YES];
        }else if(indexPath.row == 1){
            [self.navigationController pushViewController:[THJShareAppVC new] animated:YES];
        }else{
            NSString * str=@"telprompt://400-900-6014";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }
    }
}
#pragma mark  编辑信息delegate
- (void) changeTruename:(NSString *)name{
    [CInfoDic setValue:name forKey:@"truename"];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [_tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
/**
 开通企业认证
 */
-(void)ktQiyeRenZheng{
    THJaAdmitCompanyInfoVC * vc = [THJaAdmitCompanyInfoVC new];
    [self.navigationController pushViewController:vc animated:YES];
}
//点击开通合金宝
-(void)kthjbAction{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    view.backgroundColor = COLOR(0, 0, 0, 0.3);
    [window addSubview:view];
    CGFloat constant;
    if(KIsiPhoneX){
        constant = ScreenHeight/8*4+30;
    }else{
       constant = ScreenHeight/8*5;
    }
    UIImageView * imgV = [[UIImageView alloc] init];
    imgV.image = kGetImage(@"kthjb");
    imgV.frame = CGRectMake(ScreenWidth/8, ScreenHeight/8+40, ScreenWidth/4*3, constant);
    [view addSubview:imgV];
    imgV.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dailKthjb)];
    [imgV addGestureRecognizer:tap];
    
    UIButton * cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [view addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(hideView:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setBackgroundImage:kGetImage(@"cancel") forState:UIControlStateNormal];
    cancelBtn.sd_layout
    .rightEqualToView(imgV)
    .bottomSpaceToView(imgV,-30)
    .heightIs(30)
    .widthIs(30);
}
-(void)hideView:(UIButton*)btn{
    [btn.superview removeFromSuperview];
}
//电话开通合金宝
-(void)dailKthjb{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"4009996014"];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}
#pragma mark ----头像点击-----
-(void)iconTapAction{
    [self alertWithTitle1:@"取消" title2:@"拍照" title3:@"相册"];
}
#pragma mark ----更多操作---
-(void)actionSheetIndex0Function{
    NSLog(@"取消1");
}
-(void)actionSheetIndex1Function{
    [self getPhotoWithType:0];
}
-(void)actionSheetIndex2Function{
    [self getPhotoWithType:1];
}

/**
 调用相册或相机
 */
-(void)getPhotoWithType:(NSInteger)index{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (index) {
            case 0:
                //来源:相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                //来源:相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self uploadCompanyIconWithImg:image];
}
/**
 上传头像
 @param img img对象
 */
-(void)uploadCompanyIconWithImg:(UIImage*)img{

    NSString * imgDataStr = [self image2DataURL:img];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"index.php?f=member&r=member&m=save_face"];
    NSDictionary * dic = @{
                           @"face":imgDataStr,
                           };
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    [THJNetWork postDataFromUrl:urlStr parameters:dic Token:token callback:^(NSDictionary* receiveData, NSError *error) {
        NSLog(@"fanhui-%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            [CInfoDic setValue:receiveData[@"data"] forKey:@"face"];
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
            [_tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}
@end
